package com.example.hao.cameraflash;

import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.camera2.CameraManager;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button btn_open;
    private Button btn_close;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn_open = findViewById(R.id.btn_open);
        btn_close = findViewById(R.id.btn_close);
        btn_open.setOnClickListener(this);
        btn_close.setOnClickListener(this);
    }


    private CameraManager manager;
    private Camera camera;

    private void openLight() {
        //6.0及以上,但该方法前提是,摄像头没有打开(否则闪光灯的控制权被摄像头占据)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            try {
                manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
                if (manager != null) {
                    manager.setTorchMode("0", true);// "0"是主闪光灯
                }
            } catch (Exception e) {
            }
            return;
        }
        camera = Camera.open();
        Camera.Parameters parameters = camera.getParameters();
        parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
        camera.setParameters(parameters);
        camera.startPreview();
    }


    private void closeLight() {
        //6.0及以上,但该方法前提是,摄像头没有打开(否则闪光灯的控制权被摄像头占据)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            try {
                if (manager == null) {
                    return;
                }
                manager.setTorchMode("0", false);
            } catch (Exception e) {
            }
            return;
        }
        if (camera == null) {
            return;
        }
        camera.stopPreview();
        camera.release();
    }

    // 判断是否有闪光灯功能
    private boolean hasFlash() {
        return getApplicationContext().getPackageManager()
                .hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
    }

    @Override
    public void onClick(View v) {
        if (hasFlash()){
            switch (v.getId()){
                case R.id.btn_open:
                    openLight();
                    break;
                case R.id.btn_close:
                    closeLight();
                    break;
            }
        }
    }
}
